package Presentacion.ArticulosStock.ABMArticulos;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import Logica.ArticulosStock.ABMMarcasLogica;
import Modelo.Marcas;

public class ABMMarcas extends JFrame {

	private JPanel contentPane;
	private JTextField tfCodigoMarcas;
	private JTextField tfMarcas;
	private JButton btnNueva, btnGrabarYActualizar;
	private JButton btnBuscar;
	private JButton btnIzquierda;
	private JButton btnDerecha;
	private JButton btnUltimo;
	private JButton btnPrimero;

	public List<Marcas> list;
	private Marcas f;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ABMMarcas frame = new ABMMarcas();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ABMMarcas() {
		setResizable(false);
		setTitle("Alta, Baja o Modificaci\u00F3n de Marcas");
		this.setVisible(true);

		/**Pregunto si al presionar la "X" esta seguro de que quiere cerrar la ventana.*/
		this.addWindowListener(new WindowAdapter() {
	           public void windowClosing(WindowEvent e) {
	        	   setDefaultCloseOperation(0); 
	        	   cerrarVentana();
	           }
	       });
		
		setBounds(100, 100, 570, 220);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(192, 192, 192));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblFamilia = new JLabel("Denominaci\u00F3n de Marcas");
		lblFamilia.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblFamilia.setBounds(10, 11, 267, 27);
		contentPane.add(lblFamilia);
		
		tfCodigoMarcas = new JTextField();
		tfCodigoMarcas.setEditable(false);
		tfCodigoMarcas.setBounds(20, 39, 70, 25);
		contentPane.add(tfCodigoMarcas);
		tfCodigoMarcas.setColumns(10);
		
		tfMarcas = new JTextField();
		tfMarcas.addFocusListener(new FocusAdapter() {
			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfMarcas);
			}
			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfMarcas);
			}
		});
		tfMarcas.setBounds(100, 39, 300, 25);
		contentPane.add(tfMarcas);
		tfMarcas.setColumns(10);
		
		btnNueva = new JButton("<html><p>Nueva</p><p>Marca</p></html>");
		btnNueva.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				nuevo();
			}
		});
		btnNueva.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnNueva.setBounds(415, 25, 130, 55);
		contentPane.add(btnNueva);
		
		btnGrabarYActualizar = new JButton("<html><p>Grabar y</p><p>actualizar</p></html>");
		btnGrabarYActualizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				grabarActualizar();
			}
		});
		btnGrabarYActualizar.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnGrabarYActualizar.setBounds(415, 91, 130, 70);
		contentPane.add(btnGrabarYActualizar);
		
		btnBuscar = new JButton("");
		btnBuscar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				buscarFamilia();
			}
		});
		btnBuscar.setToolTipText("Buscar");
		btnBuscar.setIcon(new ImageIcon(ABMMarcas.class.getResource("/Presentacion/Img/binoculars.png")));
		btnBuscar.setBounds(185, 91, 70, 70);
		contentPane.add(btnBuscar);
		
		btnIzquierda = new JButton("");
		btnIzquierda.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				init(getPre(Integer.parseInt(tfCodigoMarcas.getText())).getIdMarcas());
			}
		});
		btnIzquierda.setToolTipText("Anterior");
		btnIzquierda.setIcon(new ImageIcon(ABMMarcas.class.getResource("/Presentacion/Img/izquierda.png")));
		btnIzquierda.setBounds(110, 91, 70, 70);
		contentPane.add(btnIzquierda);
		
		btnDerecha = new JButton("");
		btnDerecha.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				init(getPos(Integer.parseInt(tfCodigoMarcas.getText())).getIdMarcas());
			}
		});
		btnDerecha.setToolTipText("Siguiente");
		btnDerecha.setIcon(new ImageIcon(ABMMarcas.class.getResource("/Presentacion/Img/derecha.png")));
		btnDerecha.setBounds(260, 91, 70, 70);
		contentPane.add(btnDerecha);
		
		btnUltimo = new JButton("");
		btnUltimo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				init(getLast().getIdMarcas());
			}
		});
		btnUltimo.setToolTipText("Ultimo");
		btnUltimo.setIcon(new ImageIcon(ABMMarcas.class.getResource("/Presentacion/Img/ultimo.png")));
		btnUltimo.setBounds(335, 91, 70, 70);
		contentPane.add(btnUltimo);
		
		btnPrimero = new JButton("");
		btnPrimero.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				init(-1);
			}
		});
		btnPrimero.setToolTipText("Principio");
		btnPrimero.setIcon(new ImageIcon(ABMMarcas.class.getResource("/Presentacion/Img/primero.png")));
		btnPrimero.setBounds(35, 91, 70, 70);
		contentPane.add(btnPrimero);
		
		this.init(-1);
	}
	
	private void eventoTeclado() {
		 /** evento escape*/
			        KeyListener keyEscape = new KeyAdapter() {
			            public void keyPressed(KeyEvent evt) {
			                if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
			                	cerrarVentana();
			                }
			            }
			        };
		/** evento enter*/
			        KeyListener keyEnter = new KeyAdapter() {
			            public void keyPressed(KeyEvent evt) {
			                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
//			                    int i = 0;
//			                	guardar(null);
			                }
			            }
			        };

//			        
//		/**ASIGNO EVENTOS TECLADO*/
//		//PANEL
			        contentPane.addKeyListener(keyEnter);
			        contentPane.addKeyListener(keyEscape);
//		//JTEXTFIELD
			        tfCodigoMarcas.addKeyListener(keyEnter);
			        tfCodigoMarcas.addKeyListener(keyEscape);
			        
			        tfMarcas.addKeyListener(keyEnter);
			        tfMarcas.addKeyListener(keyEscape);
//			        
			        btnNueva.addKeyListener(keyEnter);
			        btnNueva.addKeyListener(keyEscape);
			        
			        btnGrabarYActualizar.addKeyListener(keyEnter);
			        btnGrabarYActualizar.addKeyListener(keyEscape);
			        
			    	btnBuscar.addKeyListener(keyEnter);
			    	btnBuscar.addKeyListener(keyEscape);
			    	
			    	btnIzquierda.addKeyListener(keyEnter);
			    	btnIzquierda.addKeyListener(keyEscape);
			    	
			    	btnDerecha.addKeyListener(keyEnter);
			    	btnDerecha.addKeyListener(keyEscape);
			    	
			    	btnUltimo.addKeyListener(keyEnter);
			    	btnUltimo.addKeyListener(keyEscape);
			    	
			    	btnPrimero.addKeyListener(keyEnter);
			    	btnPrimero.addKeyListener(keyEscape);
			    	
		       
			    }
	
	/*Metodo para confirma si esta seguro que quiere cerrar la aplicacinn*/	
	public void cerrarVentana(){
		this.setVisible(false);							    
	}
	
	/** Pinto JTEXTFIELD de color */
	public void pintaVerde(JTextField tf){
		tf.setBackground(new Color(153, 255, 153));
	}
	
	public void pintaBlanco(JTextField tf){
		tf.setBackground(new Color(255, 255, 255));
	}
	
	public void init(int id){
		list = ABMMarcasLogica.getList();
		Marcas o;
		
		if(id != -1)
			o = ABMMarcasLogica.getById(id);
		else
			o = list.get(0);
		
		tfCodigoMarcas.setText(Integer.toString(o.getIdMarcas()));
		tfMarcas.setText(o.getNombre());
	}
	
	public Marcas getPos(int id){
		return ABMMarcasLogica.getPos(id);
	}	
	public Marcas getPre(int id){
		return ABMMarcasLogica.getPre(id);
	}
	public Marcas getLast(){
		return ABMMarcasLogica.getLast();
	}
	
	public void buscarFamilia(){
		new BuscarMarcas(this);
	}
	
	public void nuevo(){
		try {
			Marcas last = ABMMarcasLogica.getLast();
			Marcas obj;
			
			tfCodigoMarcas.setText(Integer.toString(last.getIdMarcas() +1));
			tfMarcas.setText("");
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	public void grabarActualizar(){
		try {
			int id = ABMMarcasLogica.getById(Integer.parseInt(tfCodigoMarcas.getText())).getIdMarcas();
			int count = ABMMarcasLogica.countByNom(tfMarcas.getText());
			Marcas f = null;
			if (id == 0 && count == 0) //nuevo
				crear();
			
			if(id == 0 && count == 1)
				JOptionPane.showMessageDialog(null, "No se pudo crear la marca \n ERROR: Objeto existente",
						  "Error", JOptionPane.ERROR_MESSAGE);
			
			if(id != 0 && count == 1){
				f = ABMMarcasLogica.getByNom(tfMarcas.getText());
				if (id == f.getIdMarcas())
					modificar();
				else
					JOptionPane.showMessageDialog(null, "No se pudo crear la marca \n ERROR: Objeto existente",
							  "Error", JOptionPane.ERROR_MESSAGE);
			}
				
			if(id != 0 && count == 0)
				modificar();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void crear(){
		Marcas obj;
		obj = ABMMarcasLogica.getByNom(tfMarcas.getText());
		obj.setIdMarcas(Integer.parseInt(tfCodigoMarcas.getText()));
		obj.setNombre(tfMarcas.getText().toUpperCase());
		
		ABMMarcasLogica.crear(obj);
	}
	
	public void modificar(){
		Marcas obj;
		obj = ABMMarcasLogica.getByNom(tfMarcas.getText());
		obj.setIdMarcas(Integer.parseInt(tfCodigoMarcas.getText()));
		obj.setNombre(tfMarcas.getText().toUpperCase());
		
		ABMMarcasLogica.modificar(Integer.parseInt(tfCodigoMarcas.getText()), obj);
	}
}
